import Panel from "./../../elements/Panel";
import Header from "./../../components/Header";
import Modal from "./../../components/Modal/";
import {connect} from "react-redux";
import {Config, Fetch, Lang} from "./../../libs/";
import {URL, setTitle, md5Url} from "./../../libs/Url";
import Label from "./../../components/FormLabel";
import FormGroup from "./../../components/FormGroup";
import FormItem from "./../../components/FormItem";
import FormItemType from "./../../components/FormItemType";
import InputGroup from "./../../components/InputGroup";
import Selected from "./../../components/SelectItem";
import BreadcrumbNavigation from "./../../components/BreadcrumbNavigation";
import {fetch} from "../../actions";
import {SUBJECT, PAGE_SUBJECT} from "./../../actions/subject";
import {browserHistory} from 'react-router';


const AddActivity = React.createClass({
    getInitialState(){
        const self = this;
        this.isUpdate = this.props.router.params.id;
        setTitle(this.isUpdate ? Lang.title.update_activity : Lang.title.new_activity);
        this.form = [
            {
                name: 'classid',
                label: "推送班级",
                value: '',
                tips: '',
                type: FormItemType.MODAL_CHECK_BOX,
                onchange: function (index, content) {
                    self.setState({
                        form: [
                            ...self.state.form.slice(0, index),
                            Object.assign({}, self.state.form[index], {
                                value: content,
                                tips: content.length ? '' : '该项必填',
                            }),
                            ...self.state.form.slice(index + 1),
                        ]
                    });
                }
            },
            {
                name: 'classifyid',
                label: '选择分类',
                value: '',
                tips: '',
                required: true,
                inits: [],
                type: FormItemType.SELECT,
                onchange: function (index, content) {
                    self.setState({
                        form: [
                            ...self.state.form.slice(0, index),
                            Object.assign({}, self.state.form[index], {
                                value: content,
                                tips: content.length ? '' : '该项必填',
                            }),
                            ...self.state.form.slice(index + 1),
                        ]
                    });
                }
            },
            {
                name: 'name',
                label: '活动标题',
                placeholder: '',
                required: true,
                value: '',
                tips: '',
                type: FormItemType.INPUT,
                onchange: function (index, content) {
                    self.setState({
                        form: [
                            ...self.state.form.slice(0, index),
                            Object.assign({}, self.state.form[index], {
                                value: content,
                                tips: content.length ? '' : '该项必填',
                            }),
                            ...self.state.form.slice(index + 1),
                        ]
                    });
                }
            },
            {
                name: 'summary',
                label: '摘要',
                value: '',
                placeholder: '',
                tips: '',
                onchange: function (index, content) {
                    self.setState({
                        form: [
                            ...self.state.form.slice(0, index),
                            Object.assign({}, self.state.form[index], {
                                value: content,
                                tips: content.length ? '' : '该项必填',
                            }),
                            ...self.state.form.slice(index + 1),
                        ]
                    });
                }
            },
            {
                name: 'fileids',
                label: '缩略图',
                value: '',
                placeholder: '',
                tips: '',
                type: FormItemType.UPLOAD,
                onchange: function (index, content) {
                    self.setState({
                        form: [
                            ...self.state.form.slice(0, index),
                            Object.assign({}, self.state.form[index], {
                                value: content,
                                tips: content.length ? '' : '该项必填',
                            }),
                            ...self.state.form.slice(index + 1),
                        ]
                    });
                }
            },
            {
                name: 'time',
                label: '活动时间',
                value: '',
                placeholder: '',
                tips: '',
                type: FormItemType.TIME_RANGE,
                onchange: function (index, content) {
                    self.setState({
                        form: [
                            ...self.state.form.slice(0, index),
                            Object.assign({}, self.state.form[index], content || {}),
                            ...self.state.form.slice(index + 1),
                        ]
                    });
                }
            },
            {
                name: 'content',
                label: '正文',
                placeholder: '',
                value: '',
                required: true,
                tips: '',
                type: FormItemType.EDITOR,
                onchange: function (index, content) {
                    if (content == self.state.form[index].value) {
                        return;
                    }
                    self.setState({
                        form: [
                            ...self.state.form.slice(0, index),
                            Object.assign({}, self.state.form[index], {
                                value: content,
                                tips: content.length ? '' : '该项必填',
                            }),
                            ...self.state.form.slice(index + 1),
                        ]
                    })
                }
            }
        ];
        let isUpdate = this.props.router.params.id;
        return {
            open: false,
            selected: '',
            form: isUpdate ? [] : this.form,
            tips: {}
        }
    },
    setchange(index, content){
        const self = this;
        self.setState({
            form: [
                ...self.state.form.slice(0, index),
                Object.assign({}, self.state.form[index], {
                    value: content,
                    tips: content.length ? '' : '该项必填',
                }),
                ...self.state.form.slice(index + 1),
            ]
        })
    },
    componentDidMount() {
        const self = this;
        const {dispatch} = this.props;
        dispatch(fetch({url: URL.ACTIVITY_CATEGORY_FIND}));
        if (this.props.router.params.id) {
            Fetch(URL.ACTIVITY_GET, {body: {campaignid: this.props.router.params.id}})
                .then((res)=> {
                    let campaign_ = res.campaign;
                    self.form = self.form.map(item=> {
                        item.value = campaign_[item.name];
                        return item;
                    });
                    self.setState({
                        form: self.form,
                    });
                })
                .catch(e=> {
                    console.log(e);
                })
        }
        // dispatch(fetch({url: URL.ACTIVITY_GET}));
    },
    onsubmit(){
        const {dispatch, user} = this.props;
        const self = this;

        let data_category = this.props[md5Url.ACTIVITY_CATEGORY_FIND] || {};
        (!data_category.list && (data_category.list = []));
        if (!data_category.list.length)return alert('分类未设置');
        var form = {};

        self.state.form.forEach((item, index)=> {
            if (item.required && !item.value) {
                if (index == 1) {
                    form[item.name] = data_category.list[0].id;
                } else {
                    self.setState({
                        form: [
                            ...self.state.form.slice(0, index),
                            Object.assign({}, self.state.form[index], {
                                tips: '该项必填',
                            }),
                            ...self.state.form.slice(index + 1),
                        ]
                    })
                }

            } else {
                if (index == 0) {
                    if (!item.value) {
                        form[item.name] = user['class'].map(item=> {
                            return item.classid
                        }).toString()
                    } else {
                        form[item.name] = item.value;
                        if (item.value.slice(0, 1) == ',') {
                            form[item.name] = item.value.slice(1);
                        } else if (item.value.slice(item.value.length) == ',') {
                            form[item.name] = item.value.slice(0, item.value.length - 1);
                        }
                    }
                } else if (item.type == FormItemType.TIME_RANGE) {
                    form['starttime'] = (item.startDate || Moment()).format('YYYY-MM-DD');
                    form['endtime'] = (item.endDate || Moment()).format('YYYY-MM-DD');
                } else {
                    form[item.name] = item.value;
                }
            }
        });
        let isUpdate = this.props.router.params.id;

        if ((isUpdate && Object.keys(form).length >= (self.state.form.length + 1)) || (Object.keys(form).length == (self.state.form.length + 1))) {
            if (isUpdate) {
                form.campaignid = isUpdate;
            }
            Fetch(isUpdate ? URL.ACTIVITY_MODIFY : URL.ACTIVITY_ADD, {body: form, method: 'POST'})
                .then(data=> {
                    alert('成功');
                    if (!isUpdate) {
                        self.props.router.push(Config.MENUS_ABSOLUTE.ACTIVITIES)
                    }
                })
                .catch(e=> {
                    alert('失败');
                });
        }

    },
    render(){
        const self = this;
        const {user, dispatch}  = this.props;
        //const form = this.props[PAGE_SUBJECT.ACTIVITY_ADD].form;
        let data_category = this.props[md5Url.ACTIVITY_CATEGORY_FIND] || {};
        (!data_category.list && (data_category.list = []));


        return (
            <div>
                <BreadcrumbNavigation navs={[
                    {url: Config.MENUS_ABSOLUTE.HOME, label: Lang.menus.HOME},
                    {url: Config.MENUS_ABSOLUTE.ACTIVITIES, label: Lang.menus.ACTIVITIES_LIST},
                    {label: this.props.router.params.id ? Lang.menus.ACTIVITIES_UPDATE : Lang.menus.ACTIVITIES_CREATE},
                ]}/>
                <Panel>
                    <Header>{this.props.router.params.id ? Lang.menus.ACTIVITIES_UPDATE : Lang.menus.ACTIVITIES_CREATE}</Header>
                    <div className="form-horizontal">
                        {
                            self.state.form.map((item, index)=> {
                                if (item.type == FormItemType.MODAL_CHECK_BOX) {
                                    return <FormItem {...item} key={index}>
                                        <div className="homeword">
                                            {
                                                user.class.map((item_, idex)=> {
                                                    item_.checked = self.state.form[index].value.indexOf(item_.classid) > -1 ||
                                                        (!self.state.form[index].value.replace(',', '').length);
                                                    return <Selected onremove={()=> {
                                                        item.onchange(index, self.state.form[index].value.replace(item_.classid + ',', ''));
                                                    }} key={idex} {...item_} />
                                                })
                                            }
                                            <button className="btn btn-default btn-sm "
                                                    onClick={()=> {
                                                        this.setState({open: true})
                                                    }} type="button"><i className="fa fa-hand-o-up"></i> 设置推送班级
                                            </button>
                                        </div>
                                        <Modal open={self.state.open}>
                                            <Modal.Header
                                                onclose={()=> {
                                                    self.setState({open: false, selected: ''})
                                                }
                                                }>选择要推送的班级</Modal.Header>
                                            <Modal.Body >
                                                <form className="form-horizontal">
                                                    <div className="form-group">
                                                        <label className="col-sm-3 control-label">一年级：</label>
                                                        <div className="col-sm-9">
                                                            {
                                                                user.class.map((item_, idex)=> {
                                                                    return (
                                                                        <label
                                                                            className="checkbox-inline"
                                                                            key={idex}
                                                                        >
                                                                            <input
                                                                                type="checkbox"
                                                                                checked={(self.state.form[index].value.concat(self.state.selected)).indexOf(item_.classid) > -1}
                                                                                onClick={(e)=> {
                                                                                    if (e.target.checked) {
                                                                                        self.setState({
                                                                                            selected: self.state.selected + item_.classid + ','
                                                                                        })
                                                                                    } else {
                                                                                        self.setState({
                                                                                            selected: self.state.selected.replace(item_.classid + ',', '')
                                                                                        });
                                                                                    }
                                                                                }}/>
                                                                            {item_['class'] && item_['class'].name}
                                                                        </label>
                                                                    )
                                                                })
                                                            }
                                                        </div>
                                                    </div>
                                                </form>
                                            </Modal.Body>
                                            <Modal.Footer
                                                onclose={()=> {
                                                    self.setState({open: false, selected: ''})
                                                }}
                                                onconfirm={()=> {
                                                    console.log(_.union(self.state.form[index].value.split(','),
                                                        self.state.selected.split(',')))
                                                    item.onchange(index, _.union(self.state.form[index].value.split(','),
                                                            self.state.selected.split(',')).join(',') + ',')
                                                    self.setState({open: false, selected: ''})
                                                }}
                                            />
                                        </Modal>
                                    </FormItem>
                                } else if (item.type == FormItemType.SELECT) {
                                    return <FormItem {...item} key={index}>
                                        <select className="form-control"
                                                onChange={(e)=> {
                                                    item.onchange(index, e.target.value)
                                                }}
                                        >
                                            {
                                                data_category.list.map(function (item_, index) {
                                                    return <option value={item_.id} key={index}>{item_.name}</option>
                                                })
                                            }
                                        </select>
                                    </FormItem>
                                } else {
                                    return <FormItem index={index} {...item}
                                                     key={index}></FormItem>
                                }
                            })
                        }
                        <FormGroup>
                            <Label></Label>
                            <InputGroup>
                                <button onClick={self.onsubmit} className="btn btn-success" type="submit">
                                    保存
                                </button>
                            </InputGroup>
                        </FormGroup>
                    </div>
                </Panel>
            </div>
        )
    }
});
function select(state) {
    return {
        user: state.user.user,
        [md5Url.ACTIVITY_CATEGORY_FIND]: state.fetchBySubject[md5Url.ACTIVITY_CATEGORY_FIND],
        // [SUBJECT.ACTIVITY_ADD]: state.fetchBySubject[SUBJECT.ACTIVITY_ADD],
        [PAGE_SUBJECT.ACTIVITY_ADD]: state.pageBySubject[PAGE_SUBJECT.ACTIVITY_ADD]
    }
}
export default connect(select)(AddActivity)
